<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>perlfaq5 - Files and Formats - Perldoc Browser</title>
    <link rel="search" href="https://perldoc.perl.org/opensearch.xml" type="application/opensearchdescription+xml" title="Perldoc Browser">
    <link rel="canonical" href="https://perldoc.perl.org/perlfaq5">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/stackoverflow-light.min.css" integrity="sha512-cG1IdFxqipi3gqLmksLtuk13C+hBa57a6zpWxMeoY3Q9O6ooFxq50DayCdm0QrDgZjMUn23z/0PMZlgft7Yp5Q==" crossorigin="anonymous" />
    <style>
      body {
        background: #f4f4f5;
        color: #020202;
      }
      .navbar-dark {
        background-image: -webkit-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: -o-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: linear-gradient(to bottom, #005f85 0, #002e49 100%);
        filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff005f85', endColorstr='#ff002e49', GradientType=0);
        background-repeat: repeat-x;
      }
      .navbar-dark .navbar-nav .nav-link,
      .navbar-dark .navbar-nav .nav-link:focus { color: #fff }
      .navbar-dark .navbar-nav .nav-link:hover { color: #ffef68 }
      #wrapperlicious {
        margin: 0 auto;
        font: 0.9em 'Helvetica Neue', Helvetica, sans-serif;
        font-weight: normal;
        line-height: 1.5em;
        margin: 0;
        padding: 0;
      }
      #wrapperlicious h1 { font-size: 1.5em }
      #wrapperlicious h2 { font-size: 1.3em }
      #wrapperlicious h3 { font-size: 1.1em }
      #wrapperlicious h4 { font-size: 0.9em }
      #wrapperlicious h1, #wrapperlicious h2, #wrapperlicious h3,
      #wrapperlicious h4, #wrapperlicious dt {
        color: #020202;
        margin-top: 1em;
        margin-bottom: 1em;
        position: relative;
        font-weight: bold;
      }
      #wrapperlicious a { color: inherit; text-decoration: underline }
      #wrapperlicious #toc { text-decoration: none }
      #wrapperlicious a:hover { color: #2a2a2a }
      #wrapperlicious a img { border: 0 }
      #wrapperlicious :not(pre) > code {
        color: inherit;
        background-color: rgba(0, 0, 0, 0.04);
        border-radius: 3px;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        padding: 0.3em;
      }
      #wrapperlicious dd {
        margin: 0;
        margin-left: 2em;
      }
      #wrapperlicious dt {
        color: #2a2a2a;
        font-weight: bold;
        margin-left: 0.9em;
      }
      #wrapperlicious p {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious li > p {
        margin-bottom: 0;
        margin-top: 0;
      }
      #wrapperlicious pre {
        border: 1px solid #c1c1c1;
        border-radius: 3px;
        font: 100% Consolas, Menlo, Monaco, monospace;
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious pre > code {
        display: block;
        background-color: #f6f6f6;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        line-height: 1.5em;
        text-align: left;
        white-space: pre;
        padding: 1em;
      }
      #wrapperlicious dl, #wrapperlicious ol, #wrapperlicious ul {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious ul {
        list-style-type: square;
      }
      #wrapperlicious ul ul {
        margin-bottom: 0px;
        margin-top: 0px;
      }
      #footer {
        font-size: 0.8em;
        padding-top: 0.5em;
        text-align: center;
      }
      #more {
        display: inline;
        font-size: 0.8em;
      }
      #perldocdiv {
        background-color: #fff;
        border: 1px solid #c1c1c1;
        border-bottom-left-radius: 5px;
        border-bottom-right-radius: 5px;
        margin-left: auto;
        margin-right: auto;
        padding: 3em;
        padding-top: 1em;
        max-width: 960px;
      }
      #moduleversion { float: right }
      #wrapperlicious .leading-notice {
        font-style: italic;
        padding-left: 1em;
        margin-top: 1em;
        margin-bottom: 1em;
      }
      #wrapperlicious .permalink {
        display: none;
        left: -0.75em;
        position: absolute;
        padding-right: 0.25em;
        text-decoration: none;
      }
      #wrapperlicious h1:hover .permalink, #wrapperlicious h2:hover .permalink,
      #wrapperlicious h3:hover .permalink, #wrapperlicious h4:hover .permalink,
      #wrapperlicious dt:hover .permalink {
        display: block;
      }
    </style>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-KVNWBNT5FB"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'G-KVNWBNT5FB');
      gtag('config', 'UA-50555-3');
    </script>
  </head>
  <body>
    <nav class="navbar navbar-expand-md navbar-dark bg-dark justify-content-between">
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <a class="navbar-brand" href="https://perldoc.perl.org/">Perldoc Browser</a>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlfaq5.html#" id="dropdownlink-stable" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">5.35.0</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-stable">
          <a class="dropdown-item" href="https://perldoc.perl.org/perlfaq5">Latest</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.2/perlfaq5">5.38.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.1/perlfaq5">5.38.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0/perlfaq5">5.38.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.3/perlfaq5">5.36.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.2/perlfaq5">5.36.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.1/perlfaq5">5.36.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.0/perlfaq5">5.36.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.3/perlfaq5">5.34.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.2/perlfaq5">5.34.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.1/perlfaq5">5.34.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.0/perlfaq5">5.34.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.1/perlfaq5">5.32.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.0/perlfaq5">5.32.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.3/perlfaq5">5.30.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.2/perlfaq5">5.30.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.1/perlfaq5">5.30.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.0/perlfaq5">5.30.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.3/perlfaq5">5.28.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.2/perlfaq5">5.28.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.1/perlfaq5">5.28.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.0/perlfaq5">5.28.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.3/perlfaq5">5.26.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.2/perlfaq5">5.26.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.1/perlfaq5">5.26.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.0/perlfaq5">5.26.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.4/perlfaq5">5.24.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.3/perlfaq5">5.24.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.2/perlfaq5">5.24.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.1/perlfaq5">5.24.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.0/perlfaq5">5.24.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.4/perlfaq5">5.22.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.3/perlfaq5">5.22.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.2/perlfaq5">5.22.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.1/perlfaq5">5.22.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.0/perlfaq5">5.22.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.3/perlfaq5">5.20.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.2/perlfaq5">5.20.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.1/perlfaq5">5.20.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.0/perlfaq5">5.20.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.4/perlfaq5">5.18.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.3/perlfaq5">5.18.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.2/perlfaq5">5.18.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.1/perlfaq5">5.18.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.0/perlfaq5">5.18.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.3/perlfaq5">5.16.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.2/perlfaq5">5.16.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.1/perlfaq5">5.16.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.0/perlfaq5">5.16.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.4/perlfaq5">5.14.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.3/perlfaq5">5.14.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.2/perlfaq5">5.14.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.1/perlfaq5">5.14.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.0/perlfaq5">5.14.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.5/perlfaq5">5.12.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.4/perlfaq5">5.12.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.3/perlfaq5">5.12.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.2/perlfaq5">5.12.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.1/perlfaq5">5.12.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.0/perlfaq5">5.12.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.1/perlfaq5">5.10.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.0/perlfaq5">5.10.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.9/perlfaq5">5.8.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.8/perlfaq5">5.8.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.7/perlfaq5">5.8.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.6/perlfaq5">5.8.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.5/perlfaq5">5.8.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.4/perlfaq5">5.8.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.3/perlfaq5">5.8.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.2/perlfaq5">5.8.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.1/perlfaq5">5.8.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.0/perlfaq5">5.8.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.2/perlfaq5">5.6.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.1/perlfaq5">5.6.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.0/perlfaq5">5.6.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_04/perlfaq5">5.005_04</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_03/perlfaq5">5.005_03</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_02/perlfaq5">5.005_02</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_01/perlfaq5">5.005_01</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005/perlfaq5">5.005</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlfaq5.html#" id="dropdownlink-dev" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dev</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-dev">
          <a class="dropdown-item" href="https://perldoc.perl.org/blead/perlfaq5">blead</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.6/perlfaq5">5.39.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.5/perlfaq5">5.39.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.4/perlfaq5">5.39.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.3/perlfaq5">5.39.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.2/perlfaq5">5.39.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.1/perlfaq5">5.39.1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC2/perlfaq5">5.38.0-RC2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC1/perlfaq5">5.38.0-RC1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.11/perlfaq5">5.37.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.10/perlfaq5">5.37.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.9/perlfaq5">5.37.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.8/perlfaq5">5.37.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.7/perlfaq5">5.37.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.6/perlfaq5">5.37.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.5/perlfaq5">5.37.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.4/perlfaq5">5.37.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.3/perlfaq5">5.37.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.2/perlfaq5">5.37.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.1/perlfaq5">5.37.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.0/perlfaq5">5.37.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.11/perlfaq5">5.35.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.10/perlfaq5">5.35.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.9/perlfaq5">5.35.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.8/perlfaq5">5.35.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.7/perlfaq5">5.35.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.6/perlfaq5">5.35.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.5/perlfaq5">5.35.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.4/perlfaq5">5.35.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.3/perlfaq5">5.35.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.2/perlfaq5">5.35.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.1/perlfaq5">5.35.1</a>
          <a class="dropdown-item active" href="perlfaq5.html">5.35.0</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlfaq5.html#" id="dropdownlink-nav" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Documentation</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-nav">
          <a class="dropdown-item" href="perl.html">Perl</a>
          <a class="dropdown-item" href="perlintro.html">Intro</a>
          <a class="dropdown-item" href="perl.html#Tutorials">Tutorials</a>
          <a class="dropdown-item" href="perlfaq.html">FAQs</a>
          <a class="dropdown-item" href="perl.html#Reference-Manual">Reference</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlop.html">Operators</a>
          <a class="dropdown-item" href="functions.html">Functions</a>
          <a class="dropdown-item" href="variables.html">Variables</a>
          <a class="dropdown-item" href="modules.html">Modules</a>
          <a class="dropdown-item" href="perlutil.html">Utilities</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlcommunity.html">Community</a>
          <a class="dropdown-item" href="perlhist.html">History</a>
        </div>
      </li>
    </ul>
    <ul class="navbar-nav">
      <script>
        function set_expand (expand) {
          var perldocdiv = document.getElementById('perldocdiv');
          var width = window.getComputedStyle(perldocdiv).getPropertyValue('max-width');
          var expanded = (width == '' || width == 'none') ? true : false;
          if (expand === null) {
            expand = !expanded;
          }
          if ((expand && !expanded) || (!expand && expanded)) {
            perldocdiv.style.setProperty('max-width', expand ? 'none' : '960px');
            var button_classlist = document.getElementById('content-expand-button').classList;
            if (expand) {
              button_classlist.add('btn-light');
              button_classlist.remove('btn-outline-light');
            } else {
              button_classlist.add('btn-outline-light');
              button_classlist.remove('btn-light');
            }
          }
          return expand;
        }
        function toggle_expand () {
          var expand = set_expand(null);
          document.cookie = 'perldoc_expand=' + (expand ? 1 : 0) + '; path=/; expires=Tue, 19 Jan 2038 03:14:07 UTC';
        }
        function read_expand () {
          return document.cookie.split(';').some(function (item) { return item.indexOf('perldoc_expand=1') >= 0 });
        }
        if (document.readyState === 'loading') {
          document.addEventListener('DOMContentLoaded', function () {
            if (read_expand()) {
              set_expand(true);
            }
          });
        } else if (read_expand()) {
          set_expand(true);
        }
      </script>
      <button id="content-expand-button" type="button" class="btn btn-outline-light d-none d-lg-inline-block mr-2" onclick="toggle_expand()">Expand</button>
    <ul>
    <form class="form-inline" method="get" action="https://perldoc.perl.org/5.35.0/search">
      <input class="form-control mr-3" type="search" name="q" placeholder="Search" aria-label="Search">
    </form>
  </div>
</nav>

    <div id="wrapperlicious" class="container-fluid">
      <div id="perldocdiv">
        <div id="links">
          <a href="perlfaq5.html">perlfaq5</a>
          <div id="more">
            (<a href="perlfaq5.txt">source</a>,
            <a href="https://metacpan.org/pod/perlfaq5">CPAN</a>)
          </div>
        </div>
        <div class="leading-notice">
          You are viewing the version of this documentation from Perl 5.35.0.
            This is a development version of Perl.
        </div>
        <h1><a id="toc">CONTENTS</a></h1>
                  <ul>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#NAME">NAME</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#VERSION">VERSION</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#DESCRIPTION">DESCRIPTION</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-do-I-flush/unbuffer-an-output-filehandle?-Why-must-I-do-this?">How do I flush/unbuffer an output filehandle? Why must I do this?    </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-do-I-change,-delete,-or-insert-a-line-in-a-file,-or-append-to-the-beginning-of-a-file?">How do I change, delete, or insert a line in a file, or append to the beginning of a file? </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-do-I-count-the-number-of-lines-in-a-file?">How do I count the number of lines in a file?   </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-do-I-delete-the-last-N-lines-from-a-file?">How do I delete the last N lines from a file?  </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-can-I-use-Perl&#39;s-i-option-from-within-a-program?">How can I use Perl&#39;s -i option from within a program?  </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-can-I-copy-a-file?">How can I copy a file?   </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-do-I-make-a-temporary-file-name?">How do I make a temporary file name? </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-can-I-manipulate-fixed-record-length-files?">How can I manipulate fixed-record-length files?  </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-can-I-make-a-filehandle-local-to-a-subroutine?-How-do-I-pass-filehandles-between-subroutines?-How-do-I-make-an-array-of-filehandles?">How can I make a filehandle local to a subroutine? How do I pass filehandles between subroutines? How do I make an array of filehandles?   </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-can-I-use-a-filehandle-indirectly?">How can I use a filehandle indirectly? </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-can-I-open-a-filehandle-to-a-string?">How can I open a filehandle to a string?    </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-can-I-set-up-a-footer-format-to-be-used-with-write()?">How can I set up a footer format to be used with write()? </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-can-I-write()-into-a-string?">How can I write() into a string? </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-can-I-output-my-numbers-with-commas-added?">How can I output my numbers with commas added? </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-can-I-translate-tildes-(~)-in-a-filename?">How can I translate tildes (~) in a filename?  </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-come-when-I-open-a-file-read-write-it-wipes-it-out?">How come when I open a file read-write it wipes it out?     </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#Why-do-I-sometimes-get-an-%22Argument-list-too-long%22-when-I-use-%3C*%3E?">Why do I sometimes get an &quot;Argument list too long&quot; when I use &lt;*&gt;? </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-can-I-open-a-file-named-with-a-leading-%22%3E%22-or-trailing-blanks?">How can I open a file named with a leading &quot;&gt;&quot; or trailing blanks? </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-can-I-reliably-rename-a-file?">How can I reliably rename a file?    </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-can-I-lock-a-file?">How can I lock a file?   </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#Why-can&#39;t-I-just-open(FH,-%22%3Efile.lock%22)?">Why can&#39;t I just open(FH, &quot;&gt;file.lock&quot;)? </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#I-still-don&#39;t-get-locking.-I-just-want-to-increment-the-number-in-the-file.-How-can-I-do-this?">I still don&#39;t get locking. I just want to increment the number in the file. How can I do this?  </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#All-I-want-to-do-is-append-a-small-amount-of-text-to-the-end-of-a-file.-Do-I-still-have-to-use-locking?">All I want to do is append a small amount of text to the end of a file. Do I still have to use locking?  </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-do-I-randomly-update-a-binary-file?">How do I randomly update a binary file? </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-do-I-get-a-file&#39;s-timestamp-in-perl?">How do I get a file&#39;s timestamp in perl?  </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-do-I-set-a-file&#39;s-timestamp-in-perl?">How do I set a file&#39;s timestamp in perl?  </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-do-I-print-to-more-than-one-file-at-once?">How do I print to more than one file at once? </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-can-I-read-in-an-entire-file-all-at-once?">How can I read in an entire file all at once?  </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-can-I-read-in-a-file-by-paragraphs?">How can I read in a file by paragraphs? </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-can-I-read-a-single-character-from-a-file?-From-the-keyboard?">How can I read a single character from a file? From the keyboard?  </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-can-I-tell-whether-there&#39;s-a-character-waiting-on-a-filehandle?">How can I tell whether there&#39;s a character waiting on a filehandle?</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-do-I-do-a-tail-f-in-perl?">How do I do a tail -f in perl?    </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-do-I-dup()-a-filehandle-in-Perl?">How do I dup() a filehandle in Perl? </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-do-I-close-a-file-descriptor-by-number?">How do I close a file descriptor by number?   </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#Why-can&#39;t-I-use-%22C:%5Ctemp%5Cfoo%22-in-DOS-paths?-Why-doesn&#39;t-%60C:%5Ctemp%5Cfoo.exe%60-work?">Why can&#39;t I use &quot;C:\temp\foo&quot; in DOS paths? Why doesn&#39;t `C:\temp\foo.exe` work? </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#Why-doesn&#39;t-glob(%22*.*%22)-get-all-the-files?">Why doesn&#39;t glob(&quot;*.*&quot;) get all the files? </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#Why-does-Perl-let-me-delete-read-only-files?-Why-does-i-clobber-protected-files?-Isn&#39;t-this-a-bug-in-Perl?">Why does Perl let me delete read-only files? Why does -i clobber protected files? Isn&#39;t this a bug in Perl?</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-do-I-select-a-random-line-from-a-file?">How do I select a random line from a file? </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#Why-do-I-get-weird-spaces-when-I-print-an-array-of-lines?">Why do I get weird spaces when I print an array of lines?</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-do-I-traverse-a-directory-tree?">How do I traverse a directory tree?</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-do-I-delete-a-directory-tree?">How do I delete a directory tree?</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#How-do-I-copy-an-entire-directory?">How do I copy an entire directory?</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq5.html#AUTHOR-AND-COPYRIGHT">AUTHOR AND COPYRIGHT</a>
              </li>
          </ul>

      <h1 id="NAME"><a class="permalink" href="perlfaq5.html#NAME">#</a>NAME</h1>

<p>perlfaq5 - Files and Formats</p>

<h1 id="VERSION"><a class="permalink" href="perlfaq5.html#VERSION">#</a>VERSION</h1>

<p>version 5.20210411</p>

<h1 id="DESCRIPTION"><a class="permalink" href="perlfaq5.html#DESCRIPTION">#</a>DESCRIPTION</h1>

<p>This section deals with I/O and the &quot;f&quot; issues: filehandles, flushing, formats, and footers.</p>

<h2 id="How-do-I-flush/unbuffer-an-output-filehandle?-Why-must-I-do-this?"><a class="permalink" href="perlfaq5.html#How-do-I-flush/unbuffer-an-output-filehandle?-Why-must-I-do-this?">#</a><a id="How"></a><a id="How-do-I-flush-unbuffer-an-output-filehandle-Why-must-I-do-this"></a>How do I flush/unbuffer an output filehandle? Why must I do this?    </h2>

<p>(contributed by brian d foy)</p>

<p>You might like to read Mark Jason Dominus&#39;s &quot;Suffering From Buffering&quot; at <a href="http://perl.plover.com/FAQs/Buffering.html">http://perl.plover.com/FAQs/Buffering.html</a> .</p>

<p>Perl normally buffers output so it doesn&#39;t make a system call for every bit of output. By saving up output, it makes fewer expensive system calls. For instance, in this little bit of code, you want to print a dot to the screen for every line you process to watch the progress of your program. Instead of seeing a dot for every line, Perl buffers the output and you have a long wait before you see a row of 50 dots all at once:</p>

<pre><code># long wait, then row of dots all at once
while( &lt;&gt; ) {
    print &quot;.&quot;;
    print &quot;\n&quot; unless ++$count % 50;

    #... expensive line processing operations
}</code></pre>

<p>To get around this, you have to unbuffer the output filehandle, in this case, <code>STDOUT</code>. You can set the special variable <code>$|</code> to a true value (mnemonic: making your filehandles &quot;piping hot&quot;):</p>

<pre><code>$|++;

# dot shown immediately
while( &lt;&gt; ) {
    print &quot;.&quot;;
    print &quot;\n&quot; unless ++$count % 50;

    #... expensive line processing operations
}</code></pre>

<p>The <code>$|</code> is one of the per-filehandle special variables, so each filehandle has its own copy of its value. If you want to merge standard output and standard error for instance, you have to unbuffer each (although STDERR might be unbuffered by default):</p>

<pre><code>{
    my $previous_default = select(STDOUT);  # save previous default
    $|++;                                   # autoflush STDOUT
    select(STDERR);
    $|++;                                   # autoflush STDERR, to be sure
    select($previous_default);              # restore previous default
}

# now should alternate . and +
while( 1 ) {
    sleep 1;
    print STDOUT &quot;.&quot;;
    print STDERR &quot;+&quot;;
    print STDOUT &quot;\n&quot; unless ++$count % 25;
}</code></pre>

<p>Besides the <code>$|</code> special variable, you can use <code>binmode</code> to give your filehandle a <code>:unix</code> layer, which is unbuffered:</p>

<pre><code>binmode( STDOUT, &quot;:unix&quot; );

while( 1 ) {
    sleep 1;
    print &quot;.&quot;;
    print &quot;\n&quot; unless ++$count % 50;
}</code></pre>

<p>For more information on output layers, see the entries for <code>binmode</code> and <a href="open.html">open</a> in <a href="perlfunc.html">perlfunc</a>, and the <a href="PerlIO.html">PerlIO</a> module documentation.</p>

<p>If you are using <a href="./IO::Handle.html">IO::Handle</a> or one of its subclasses, you can call the <code>autoflush</code> method to change the settings of the filehandle:</p>

<pre><code>use IO::Handle;
open my( $io_fh ), &quot;&gt;&quot;, &quot;output.txt&quot;;
$io_fh-&gt;autoflush(1);</code></pre>

<p>The <a href="./IO::Handle.html">IO::Handle</a> objects also have a <code>flush</code> method. You can flush the buffer any time you want without auto-buffering</p>

<pre><code>$io_fh-&gt;flush;</code></pre>

<h2 id="How-do-I-change,-delete,-or-insert-a-line-in-a-file,-or-append-to-the-beginning-of-a-file?"><a class="permalink" href="perlfaq5.html#How-do-I-change,-delete,-or-insert-a-line-in-a-file,-or-append-to-the-beginning-of-a-file?">#</a><a id="How1"></a><a id="How-do-I-change-delete-or-insert-a-line-in-a-file-or-append-to-the-beginning-of-a-file"></a>How do I change, delete, or insert a line in a file, or append to the beginning of a file? </h2>

<p>(contributed by brian d foy)</p>

<p>The basic idea of inserting, changing, or deleting a line from a text file involves reading and printing the file to the point you want to make the change, making the change, then reading and printing the rest of the file. Perl doesn&#39;t provide random access to lines (especially since the record input separator, <code>$/</code>, is mutable), although modules such as <a href="./Tie::File.html">Tie::File</a> can fake it.</p>

<p>A Perl program to do these tasks takes the basic form of opening a file, printing its lines, then closing the file:</p>

<pre><code>open my $in,  &#39;&lt;&#39;,  $file      or die &quot;Can&#39;t read old file: $!&quot;;
open my $out, &#39;&gt;&#39;, &quot;$file.new&quot; or die &quot;Can&#39;t write new file: $!&quot;;

while( &lt;$in&gt; ) {
        print $out $_;
}

close $out;</code></pre>

<p>Within that basic form, add the parts that you need to insert, change, or delete lines.</p>

<p>To prepend lines to the beginning, print those lines before you enter the loop that prints the existing lines.</p>

<pre><code>open my $in,  &#39;&lt;&#39;,  $file      or die &quot;Can&#39;t read old file: $!&quot;;
open my $out, &#39;&gt;&#39;, &quot;$file.new&quot; or die &quot;Can&#39;t write new file: $!&quot;;

print $out &quot;# Add this line to the top\n&quot;; # &lt;--- HERE&#39;S THE MAGIC

while( &lt;$in&gt; ) {
        print $out $_;
}

close $out;</code></pre>

<p>To change existing lines, insert the code to modify the lines inside the <code>while</code> loop. In this case, the code finds all lowercased versions of &quot;perl&quot; and uppercases them. The happens for every line, so be sure that you&#39;re supposed to do that on every line!</p>

<pre><code>open my $in,  &#39;&lt;&#39;,  $file      or die &quot;Can&#39;t read old file: $!&quot;;
open my $out, &#39;&gt;&#39;, &quot;$file.new&quot; or die &quot;Can&#39;t write new file: $!&quot;;

print $out &quot;# Add this line to the top\n&quot;;

while( &lt;$in&gt; ) {
    s/\b(perl)\b/Perl/g;
    print $out $_;
}

close $out;</code></pre>

<p>To change only a particular line, the input line number, <code>$.</code>, is useful. First read and print the lines up to the one you want to change. Next, read the single line you want to change, change it, and print it. After that, read the rest of the lines and print those:</p>

<pre><code>while( &lt;$in&gt; ) { # print the lines before the change
    print $out $_;
    last if $. == 4; # line number before change
}

my $line = &lt;$in&gt;;
$line =~ s/\b(perl)\b/Perl/g;
print $out $line;

while( &lt;$in&gt; ) { # print the rest of the lines
    print $out $_;
}</code></pre>

<p>To skip lines, use the looping controls. The <code>next</code> in this example skips comment lines, and the <code>last</code> stops all processing once it encounters either <code>__END__</code> or <code>__DATA__</code>.</p>

<pre><code>while( &lt;$in&gt; ) {
    next if /^\s+#/;             # skip comment lines
    last if /^__(END|DATA)__$/;  # stop at end of code marker
    print $out $_;
}</code></pre>

<p>Do the same sort of thing to delete a particular line by using <code>next</code> to skip the lines you don&#39;t want to show up in the output. This example skips every fifth line:</p>

<pre><code>while( &lt;$in&gt; ) {
    next unless $. % 5;
    print $out $_;
}</code></pre>

<p>If, for some odd reason, you really want to see the whole file at once rather than processing line-by-line, you can slurp it in (as long as you can fit the whole thing in memory!):</p>

<pre><code>open my $in,  &#39;&lt;&#39;,  $file      or die &quot;Can&#39;t read old file: $!&quot;
open my $out, &#39;&gt;&#39;, &quot;$file.new&quot; or die &quot;Can&#39;t write new file: $!&quot;;

my $content = do { local $/; &lt;$in&gt; }; # slurp!

    # do your magic here

print $out $content;</code></pre>

<p>Modules such as <a href="./Path::Tiny.html">Path::Tiny</a> and <a href="./Tie::File.html">Tie::File</a> can help with that too. If you can, however, avoid reading the entire file at once. Perl won&#39;t give that memory back to the operating system until the process finishes.</p>

<p>You can also use Perl one-liners to modify a file in-place. The following changes all &#39;Fred&#39; to &#39;Barney&#39; in <i>inFile.txt</i>, overwriting the file with the new contents. With the <code>-p</code> switch, Perl wraps a <code>while</code> loop around the code you specify with <code>-e</code>, and <code>-i</code> turns on in-place editing. The current line is in <code>$_</code>. With <code>-p</code>, Perl automatically prints the value of <code>$_</code> at the end of the loop. See <a href="perlrun.html">perlrun</a> for more details.</p>

<pre><code class="plaintext">perl -pi -e &#39;s/Fred/Barney/&#39; inFile.txt</code></pre>

<p>To make a backup of <code>inFile.txt</code>, give <code>-i</code> a file extension to add:</p>

<pre><code class="plaintext">perl -pi.bak -e &#39;s/Fred/Barney/&#39; inFile.txt</code></pre>

<p>To change only the fifth line, you can add a test checking <code>$.</code>, the input line number, then only perform the operation when the test passes:</p>

<pre><code class="plaintext">perl -pi -e &#39;s/Fred/Barney/ if $. == 5&#39; inFile.txt</code></pre>

<p>To add lines before a certain line, you can add a line (or lines!) before Perl prints <code>$_</code>:</p>

<pre><code class="plaintext">perl -pi -e &#39;print &quot;Put before third line\n&quot; if $. == 3&#39; inFile.txt</code></pre>

<p>You can even add a line to the beginning of a file, since the current line prints at the end of the loop:</p>

<pre><code class="plaintext">perl -pi -e &#39;print &quot;Put before first line\n&quot; if $. == 1&#39; inFile.txt</code></pre>

<p>To insert a line after one already in the file, use the <code>-n</code> switch. It&#39;s just like <code>-p</code> except that it doesn&#39;t print <code>$_</code> at the end of the loop, so you have to do that yourself. In this case, print <code>$_</code> first, then print the line that you want to add.</p>

<pre><code class="plaintext">perl -ni -e &#39;print; print &quot;Put after fifth line\n&quot; if $. == 5&#39; inFile.txt</code></pre>

<p>To delete lines, only print the ones that you want.</p>

<pre><code class="plaintext">perl -ni -e &#39;print if /d/&#39; inFile.txt</code></pre>

<h2 id="How-do-I-count-the-number-of-lines-in-a-file?"><a class="permalink" href="perlfaq5.html#How-do-I-count-the-number-of-lines-in-a-file?">#</a><a id="How2"></a><a id="How-do-I-count-the-number-of-lines-in-a-file"></a>How do I count the number of lines in a file?   </h2>

<p>(contributed by brian d foy)</p>

<p>Conceptually, the easiest way to count the lines in a file is to simply read them and count them:</p>

<pre><code>my $count = 0;
while( &lt;$fh&gt; ) { $count++; }</code></pre>

<p>You don&#39;t really have to count them yourself, though, since Perl already does that with the <code>$.</code> variable, which is the current line number from the last filehandle read:</p>

<pre><code>1 while( &lt;$fh&gt; );
my $count = $.;</code></pre>

<p>If you want to use <code>$.</code>, you can reduce it to a simple one-liner, like one of these:</p>

<pre><code class="plaintext">% perl -lne &#39;} print $.; {&#39;    file

% perl -lne &#39;END { print $. }&#39; file</code></pre>

<p>Those can be rather inefficient though. If they aren&#39;t fast enough for you, you might just read chunks of data and count the number of newlines:</p>

<pre><code>my $lines = 0;
open my($fh), &#39;&lt;:raw&#39;, $filename or die &quot;Can&#39;t open $filename: $!&quot;;
while( sysread $fh, $buffer, 4096 ) {
    $lines += ( $buffer =~ tr/\n// );
}
close $fh;</code></pre>

<p>However, that doesn&#39;t work if the line ending isn&#39;t a newline. You might change that <code>tr///</code> to a <code>s///</code> so you can count the number of times the input record separator, <code>$/</code>, shows up:</p>

<pre><code>my $lines = 0;
open my($fh), &#39;&lt;:raw&#39;, $filename or die &quot;Can&#39;t open $filename: $!&quot;;
while( sysread $fh, $buffer, 4096 ) {
    $lines += ( $buffer =~ s|$/||g; );
}
close $fh;</code></pre>

<p>If you don&#39;t mind shelling out, the <code>wc</code> command is usually the fastest, even with the extra interprocess overhead. Ensure that you have an untainted filename though:</p>

<pre><code>#!perl -T

$ENV{PATH} = undef;

my $lines;
if( $filename =~ /^([0-9a-z_.]+)\z/ ) {
    $lines = `/usr/bin/wc -l $1`
    chomp $lines;
}</code></pre>

<h2 id="How-do-I-delete-the-last-N-lines-from-a-file?"><a class="permalink" href="perlfaq5.html#How-do-I-delete-the-last-N-lines-from-a-file?">#</a><a id="How3"></a><a id="How-do-I-delete-the-last-N-lines-from-a-file"></a>How do I delete the last N lines from a file?  </h2>

<p>(contributed by brian d foy)</p>

<p>The easiest conceptual solution is to count the lines in the file then start at the beginning and print the number of lines (minus the last N) to a new file.</p>

<p>Most often, the real question is how you can delete the last N lines without making more than one pass over the file, or how to do it without a lot of copying. The easy concept is the hard reality when you might have millions of lines in your file.</p>

<p>One trick is to use <a href="./File::ReadBackwards.html">File::ReadBackwards</a>, which starts at the end of the file. That module provides an object that wraps the real filehandle to make it easy for you to move around the file. Once you get to the spot you need, you can get the actual filehandle and work with it as normal. In this case, you get the file position at the end of the last line you want to keep and truncate the file to that point:</p>

<pre><code>use File::ReadBackwards;

my $filename = &#39;test.txt&#39;;
my $Lines_to_truncate = 2;

my $bw = File::ReadBackwards-&gt;new( $filename )
    or die &quot;Could not read backwards in [$filename]: $!&quot;;

my $lines_from_end = 0;
until( $bw-&gt;eof or $lines_from_end == $Lines_to_truncate ) {
    print &quot;Got: &quot;, $bw-&gt;readline;
    $lines_from_end++;
}

truncate( $filename, $bw-&gt;tell );</code></pre>

<p>The <a href="./File::ReadBackwards.html">File::ReadBackwards</a> module also has the advantage of setting the input record separator to a regular expression.</p>

<p>You can also use the <a href="./Tie::File.html">Tie::File</a> module which lets you access the lines through a tied array. You can use normal array operations to modify your file, including setting the last index and using <code>splice</code>.</p>

<h2 id="How-can-I-use-Perl&#39;s-i-option-from-within-a-program?"><a class="permalink" href="perlfaq5.html#How-can-I-use-Perl&#39;s-i-option-from-within-a-program?">#</a><a id="How4"></a><a id="How-can-I-use-Perls--i-option-from-within-a-program"></a>How can I use Perl&#39;s <code>-i</code> option from within a program?  </h2>

<p><code>-i</code> sets the value of Perl&#39;s <code>$^I</code> variable, which in turn affects the behavior of <code>&lt;&gt;</code>; see <a href="perlrun.html">perlrun</a> for more details. By modifying the appropriate variables directly, you can get the same behavior within a larger program. For example:</p>

<pre><code># ...
{
    local($^I, @ARGV) = (&#39;.orig&#39;, glob(&quot;*.c&quot;));
    while (&lt;&gt;) {
        if ($. == 1) {
            print &quot;This line should appear at the top of each file\n&quot;;
        }
        s/\b(p)earl\b/${1}erl/i;        # Correct typos, preserving case
        print;
        close ARGV if eof;              # Reset $.
    }
}
# $^I and @ARGV return to their old values here</code></pre>

<p>This block modifies all the <code>.c</code> files in the current directory, leaving a backup of the original data from each file in a new <code>.c.orig</code> file.</p>

<h2 id="How-can-I-copy-a-file?"><a class="permalink" href="perlfaq5.html#How-can-I-copy-a-file?">#</a><a id="How5"></a><a id="How-can-I-copy-a-file"></a>How can I copy a file?   </h2>

<p>(contributed by brian d foy)</p>

<p>Use the <a href="./File::Copy.html">File::Copy</a> module. It comes with Perl and can do a true copy across file systems, and it does its magic in a portable fashion.</p>

<pre><code>use File::Copy;

copy( $original, $new_copy ) or die &quot;Copy failed: $!&quot;;</code></pre>

<p>If you can&#39;t use <a href="./File::Copy.html">File::Copy</a>, you&#39;ll have to do the work yourself: open the original file, open the destination file, then print to the destination file as you read the original. You also have to remember to copy the permissions, owner, and group to the new file.</p>

<h2 id="How-do-I-make-a-temporary-file-name?"><a class="permalink" href="perlfaq5.html#How-do-I-make-a-temporary-file-name?">#</a><a id="How6"></a><a id="How-do-I-make-a-temporary-file-name"></a>How do I make a temporary file name? </h2>

<p>If you don&#39;t need to know the name of the file, you can use <code>open()</code> with <code>undef</code> in place of the file name. In Perl 5.8 or later, the <code>open()</code> function creates an anonymous temporary file:</p>

<pre><code>open my $tmp, &#39;+&gt;&#39;, undef or die $!;</code></pre>

<p>Otherwise, you can use the File::Temp module.</p>

<pre><code>use File::Temp qw/ tempfile tempdir /;

my $dir = tempdir( CLEANUP =&gt; 1 );
($fh, $filename) = tempfile( DIR =&gt; $dir );

# or if you don&#39;t need to know the filename

my $fh = tempfile( DIR =&gt; $dir );</code></pre>

<p>The File::Temp has been a standard module since Perl 5.6.1. If you don&#39;t have a modern enough Perl installed, use the <code>new_tmpfile</code> class method from the IO::File module to get a filehandle opened for reading and writing. Use it if you don&#39;t need to know the file&#39;s name:</p>

<pre><code>use IO::File;
my $fh = IO::File-&gt;new_tmpfile()
    or die &quot;Unable to make new temporary file: $!&quot;;</code></pre>

<p>If you&#39;re committed to creating a temporary file by hand, use the process ID and/or the current time-value. If you need to have many temporary files in one process, use a counter:</p>

<pre><code>BEGIN {
    use Fcntl;
    use File::Spec;
    my $temp_dir  = File::Spec-&gt;tmpdir();
    my $file_base = sprintf &quot;%d-%d-0000&quot;, $$, time;
    my $base_name = File::Spec-&gt;catfile($temp_dir, $file_base);

    sub temp_file {
        my $fh;
        my $count = 0;
        until( defined(fileno($fh)) || $count++ &gt; 100 ) {
            $base_name =~ s/-(\d+)$/&quot;-&quot; . (1 + $1)/e;
            # O_EXCL is required for security reasons.
            sysopen $fh, $base_name, O_WRONLY|O_EXCL|O_CREAT;
        }

        if( defined fileno($fh) ) {
            return ($fh, $base_name);
        }
        else {
            return ();
        }
    }
}</code></pre>

<h2 id="How-can-I-manipulate-fixed-record-length-files?"><a class="permalink" href="perlfaq5.html#How-can-I-manipulate-fixed-record-length-files?">#</a><a id="How7"></a><a id="How-can-I-manipulate-fixed-record-length-files"></a>How can I manipulate fixed-record-length files?  </h2>

<p>The most efficient way is using <a href="perlfunc.html#pack">pack()</a> and <a href="perlfunc.html#unpack">unpack()</a>. This is faster than using <a href="perlfunc.html#substr">substr()</a> when taking many, many strings. It is slower for just a few.</p>

<p>Here is a sample chunk of code to break up and put back together again some fixed-format input lines, in this case from the output of a normal, Berkeley-style ps:</p>

<pre><code># sample input line:
#   15158 p5  T      0:00 perl /home/tchrist/scripts/now-what
my $PS_T = &#39;A6 A4 A7 A5 A*&#39;;
open my $ps, &#39;-|&#39;, &#39;ps&#39;;
print scalar &lt;$ps&gt;;
my @fields = qw( pid tt stat time command );
while (&lt;$ps&gt;) {
    my %process;
    @process{@fields} = unpack($PS_T, $_);
    for my $field ( @fields ) {
        print &quot;$field: &lt;$process{$field}&gt;\n&quot;;
    }
    print &#39;line=&#39;, pack($PS_T, @process{@fields} ), &quot;\n&quot;;
}</code></pre>

<p>We&#39;ve used a hash slice in order to easily handle the fields of each row. Storing the keys in an array makes it easy to operate on them as a group or loop over them with <code>for</code>. It also avoids polluting the program with global variables and using symbolic references.</p>

<h2 id="How-can-I-make-a-filehandle-local-to-a-subroutine?-How-do-I-pass-filehandles-between-subroutines?-How-do-I-make-an-array-of-filehandles?"><a class="permalink" href="perlfaq5.html#How-can-I-make-a-filehandle-local-to-a-subroutine?-How-do-I-pass-filehandles-between-subroutines?-How-do-I-make-an-array-of-filehandles?">#</a><a id="How8"></a><a id="How-can-I-make-a-filehandle-local-to-a-subroutine-How-do-I-pass-filehandles-between-subroutines-How-do-I-make-an-array-of-filehandles"></a>How can I make a filehandle local to a subroutine? How do I pass filehandles between subroutines? How do I make an array of filehandles?   </h2>

<p>As of perl5.6, open() autovivifies file and directory handles as references if you pass it an uninitialized scalar variable. You can then pass these references just like any other scalar, and use them in the place of named handles.</p>

<pre><code>open my    $fh, $file_name;

open local $fh, $file_name;

print $fh &quot;Hello World!\n&quot;;

process_file( $fh );</code></pre>

<p>If you like, you can store these filehandles in an array or a hash. If you access them directly, they aren&#39;t simple scalars and you need to give <code>print</code> a little help by placing the filehandle reference in braces. Perl can only figure it out on its own when the filehandle reference is a simple scalar.</p>

<pre><code>my @fhs = ( $fh1, $fh2, $fh3 );

for( $i = 0; $i &lt;= $#fhs; $i++ ) {
    print {$fhs[$i]} &quot;just another Perl answer, \n&quot;;
}</code></pre>

<p>Before perl5.6, you had to deal with various typeglob idioms which you may see in older code.</p>

<pre><code>open FILE, &quot;&gt; $filename&quot;;
process_typeglob(   *FILE );
process_reference( \*FILE );

sub process_typeglob  { local *FH = shift; print FH  &quot;Typeglob!&quot; }
sub process_reference { local $fh = shift; print $fh &quot;Reference!&quot; }</code></pre>

<p>If you want to create many anonymous handles, you should check out the Symbol or IO::Handle modules.</p>

<h2 id="How-can-I-use-a-filehandle-indirectly?"><a class="permalink" href="perlfaq5.html#How-can-I-use-a-filehandle-indirectly?">#</a><a id="How9"></a><a id="How-can-I-use-a-filehandle-indirectly"></a>How can I use a filehandle indirectly? </h2>

<p>An indirect filehandle is the use of something other than a symbol in a place that a filehandle is expected. Here are ways to get indirect filehandles:</p>

<pre><code>$fh =   SOME_FH;       # bareword is strict-subs hostile
$fh =  &quot;SOME_FH&quot;;      # strict-refs hostile; same package only
$fh =  *SOME_FH;       # typeglob
$fh = \*SOME_FH;       # ref to typeglob (bless-able)
$fh =  *SOME_FH{IO};   # blessed IO::Handle from *SOME_FH typeglob</code></pre>

<p>Or, you can use the <code>new</code> method from one of the IO::* modules to create an anonymous filehandle and store that in a scalar variable.</p>

<pre><code>use IO::Handle;                     # 5.004 or higher
my $fh = IO::Handle-&gt;new();</code></pre>

<p>Then use any of those as you would a normal filehandle. Anywhere that Perl is expecting a filehandle, an indirect filehandle may be used instead. An indirect filehandle is just a scalar variable that contains a filehandle. Functions like <code>print</code>, <code>open</code>, <code>seek</code>, or the <code>&lt;FH&gt;</code> diamond operator will accept either a named filehandle or a scalar variable containing one:</p>

<pre><code>($ifh, $ofh, $efh) = (*STDIN, *STDOUT, *STDERR);
print $ofh &quot;Type it: &quot;;
my $got = &lt;$ifh&gt;
print $efh &quot;What was that: $got&quot;;</code></pre>

<p>If you&#39;re passing a filehandle to a function, you can write the function in two ways:</p>

<pre><code>sub accept_fh {
    my $fh = shift;
    print $fh &quot;Sending to indirect filehandle\n&quot;;
}</code></pre>

<p>Or it can localize a typeglob and use the filehandle directly:</p>

<pre><code>sub accept_fh {
    local *FH = shift;
    print  FH &quot;Sending to localized filehandle\n&quot;;
}</code></pre>

<p>Both styles work with either objects or typeglobs of real filehandles. (They might also work with strings under some circumstances, but this is risky.)</p>

<pre><code>accept_fh(*STDOUT);
accept_fh($handle);</code></pre>

<p>In the examples above, we assigned the filehandle to a scalar variable before using it. That is because only simple scalar variables, not expressions or subscripts of hashes or arrays, can be used with built-ins like <code>print</code>, <code>printf</code>, or the diamond operator. Using something other than a simple scalar variable as a filehandle is illegal and won&#39;t even compile:</p>

<pre><code>my @fd = (*STDIN, *STDOUT, *STDERR);
print $fd[1] &quot;Type it: &quot;;                           # WRONG
my $got = &lt;$fd[0]&gt;                                  # WRONG
print $fd[2] &quot;What was that: $got&quot;;                 # WRONG</code></pre>

<p>With <code>print</code> and <code>printf</code>, you get around this by using a block and an expression where you would place the filehandle:</p>

<pre><code>print  { $fd[1] } &quot;funny stuff\n&quot;;
printf { $fd[1] } &quot;Pity the poor %x.\n&quot;, 3_735_928_559;
# Pity the poor deadbeef.</code></pre>

<p>That block is a proper block like any other, so you can put more complicated code there. This sends the message out to one of two places:</p>

<pre><code>my $ok = -x &quot;/bin/cat&quot;;
print { $ok ? $fd[1] : $fd[2] } &quot;cat stat $ok\n&quot;;
print { $fd[ 1+ ($ok || 0) ]  } &quot;cat stat $ok\n&quot;;</code></pre>

<p>This approach of treating <code>print</code> and <code>printf</code> like object methods calls doesn&#39;t work for the diamond operator. That&#39;s because it&#39;s a real operator, not just a function with a comma-less argument. Assuming you&#39;ve been storing typeglobs in your structure as we did above, you can use the built-in function named <code>readline</code> to read a record just as <code>&lt;&gt;</code> does. Given the initialization shown above for @fd, this would work, but only because readline() requires a typeglob. It doesn&#39;t work with objects or strings, which might be a bug we haven&#39;t fixed yet.</p>

<pre><code>$got = readline($fd[0]);</code></pre>

<p>Let it be noted that the flakiness of indirect filehandles is not related to whether they&#39;re strings, typeglobs, objects, or anything else. It&#39;s the syntax of the fundamental operators. Playing the object game doesn&#39;t help you at all here.</p>

<h2 id="How-can-I-open-a-filehandle-to-a-string?"><a class="permalink" href="perlfaq5.html#How-can-I-open-a-filehandle-to-a-string?">#</a><a id="How10"></a><a id="How-can-I-open-a-filehandle-to-a-string"></a>How can I open a filehandle to a string?    </h2>

<p>(contributed by Peter J. Holzer, hjp-usenet2@hjp.at)</p>

<p>Since Perl 5.8.0 a file handle referring to a string can be created by calling open with a reference to that string instead of the filename. This file handle can then be used to read from or write to the string:</p>

<pre><code>open(my $fh, &#39;&gt;&#39;, \$string) or die &quot;Could not open string for writing&quot;;
print $fh &quot;foo\n&quot;;
print $fh &quot;bar\n&quot;;    # $string now contains &quot;foo\nbar\n&quot;

open(my $fh, &#39;&lt;&#39;, \$string) or die &quot;Could not open string for reading&quot;;
my $x = &lt;$fh&gt;;    # $x now contains &quot;foo\n&quot;</code></pre>

<p>With older versions of Perl, the <a href="./IO::String.html">IO::String</a> module provides similar functionality.</p>

<h2 id="How-can-I-set-up-a-footer-format-to-be-used-with-write()?"><a class="permalink" href="perlfaq5.html#How-can-I-set-up-a-footer-format-to-be-used-with-write()?">#</a><a id="How11"></a><a id="How-can-I-set-up-a-footer-format-to-be-used-with-write"></a>How can I set up a footer format to be used with write()? </h2>

<p>There&#39;s no builtin way to do this, but <a href="perlform.html">perlform</a> has a couple of techniques to make it possible for the intrepid hacker.</p>

<h2 id="How-can-I-write()-into-a-string?"><a class="permalink" href="perlfaq5.html#How-can-I-write()-into-a-string?">#</a><a id="How12"></a><a id="How-can-I-write-into-a-string"></a>How can I write() into a string? </h2>

<p>(contributed by brian d foy)</p>

<p>If you want to <code>write</code> into a string, you just have to &lt;open&gt; a filehandle to a string, which Perl has been able to do since Perl 5.6:</p>

<pre><code>open FH, &#39;&gt;&#39;, \my $string;
write( FH );</code></pre>

<p>Since you want to be a good programmer, you probably want to use a lexical filehandle, even though formats are designed to work with bareword filehandles since the default format names take the filehandle name. However, you can control this with some Perl special per-filehandle variables: <code>$^</code>, which names the top-of-page format, and <code>$~</code> which shows the line format. You have to change the default filehandle to set these variables:</p>

<pre><code>open my($fh), &#39;&gt;&#39;, \my $string;

{ # set per-filehandle variables
    my $old_fh = select( $fh );
    $~ = &#39;ANIMAL&#39;;
    $^ = &#39;ANIMAL_TOP&#39;;
    select( $old_fh );
}

format ANIMAL_TOP =
 ID  Type    Name
.

format ANIMAL =
@##   @&lt;&lt;&lt;    @&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;
$id,  $type,  $name
.</code></pre>

<p>Although write can work with lexical or package variables, whatever variables you use have to scope in the format. That most likely means you&#39;ll want to localize some package variables:</p>

<pre><code>{
    local( $id, $type, $name ) = qw( 12 cat Buster );
    write( $fh );
}

print $string;</code></pre>

<p>There are also some tricks that you can play with <code>formline</code> and the accumulator variable <code>$^A</code>, but you lose a lot of the value of formats since <code>formline</code> won&#39;t handle paging and so on. You end up reimplementing formats when you use them.</p>

<h2 id="How-can-I-output-my-numbers-with-commas-added?"><a class="permalink" href="perlfaq5.html#How-can-I-output-my-numbers-with-commas-added?">#</a><a id="How13"></a><a id="How-can-I-output-my-numbers-with-commas-added"></a>How can I output my numbers with commas added? </h2>

<p>(contributed by brian d foy and Benjamin Goldberg)</p>

<p>You can use <a href="./Number::Format.html">Number::Format</a> to separate places in a number. It handles locale information for those of you who want to insert full stops instead (or anything else that they want to use, really).</p>

<p>This subroutine will add commas to your number:</p>

<pre><code>sub commify {
    local $_  = shift;
    1 while s/^([-+]?\d+)(\d{3})/$1,$2/;
    return $_;
}</code></pre>

<p>This regex from Benjamin Goldberg will add commas to numbers:</p>

<pre><code>s/(^[-+]?\d+?(?=(?&gt;(?:\d{3})+)(?!\d))|\G\d{3}(?=\d))/$1,/g;</code></pre>

<p>It is easier to see with comments:</p>

<pre><code>s/(
    ^[-+]?             # beginning of number.
    \d+?               # first digits before first comma
    (?=                # followed by, (but not included in the match) :
        (?&gt;(?:\d{3})+) # some positive multiple of three digits.
        (?!\d)         # an *exact* multiple, not x * 3 + 1 or whatever.
    )
    |                  # or:
    \G\d{3}            # after the last group, get three digits
    (?=\d)             # but they have to have more digits after them.
)/$1,/xg;</code></pre>

<h2 id="How-can-I-translate-tildes-(~)-in-a-filename?"><a class="permalink" href="perlfaq5.html#How-can-I-translate-tildes-(~)-in-a-filename?">#</a><a id="How14"></a><a id="How-can-I-translate-tildes-in-a-filename"></a>How can I translate tildes (~) in a filename?  </h2>

<p>Use the &lt;&gt; (<code>glob()</code>) operator, documented in <a href="perlfunc.html">perlfunc</a>. Versions of Perl older than 5.6 require that you have a shell installed that groks tildes. Later versions of Perl have this feature built in. The <a href="./File::KGlob.html">File::KGlob</a> module (available from CPAN) gives more portable glob functionality.</p>

<p>Within Perl, you may use this directly:</p>

<pre><code>$filename =~ s{
  ^ ~             # find a leading tilde
  (               # save this in $1
      [^/]        # a non-slash character
            *     # repeated 0 or more times (0 means me)
  )
}{
  $1
      ? (getpwnam($1))[7]
      : ( $ENV{HOME} || $ENV{LOGDIR} )
}ex;</code></pre>

<h2 id="How-come-when-I-open-a-file-read-write-it-wipes-it-out?"><a class="permalink" href="perlfaq5.html#How-come-when-I-open-a-file-read-write-it-wipes-it-out?">#</a><a id="How15"></a><a id="How-come-when-I-open-a-file-read-write-it-wipes-it-out"></a>How come when I open a file read-write it wipes it out?     </h2>

<p>Because you&#39;re using something like this, which truncates the file <i>then</i> gives you read-write access:</p>

<pre><code>open my $fh, &#39;+&gt;&#39;, &#39;/path/name&#39;; # WRONG (almost always)</code></pre>

<p>Whoops. You should instead use this, which will fail if the file doesn&#39;t exist:</p>

<pre><code>open my $fh, &#39;+&lt;&#39;, &#39;/path/name&#39;; # open for update</code></pre>

<p>Using &quot;&gt;&quot; always clobbers or creates. Using &quot;&lt;&quot; never does either. The &quot;+&quot; doesn&#39;t change this.</p>

<p>Here are examples of many kinds of file opens. Those using <code>sysopen</code> all assume that you&#39;ve pulled in the constants from <a href="Fcntl.html">Fcntl</a>:</p>

<pre><code>use Fcntl;</code></pre>

<p>To open file for reading:</p>

<pre><code>open my $fh, &#39;&lt;&#39;, $path                               or die $!;
sysopen my $fh, $path, O_RDONLY                       or die $!;</code></pre>

<p>To open file for writing, create new file if needed or else truncate old file:</p>

<pre><code>open my $fh, &#39;&gt;&#39;, $path                               or die $!;
sysopen my $fh, $path, O_WRONLY|O_TRUNC|O_CREAT       or die $!;
sysopen my $fh, $path, O_WRONLY|O_TRUNC|O_CREAT, 0666 or die $!;</code></pre>

<p>To open file for writing, create new file, file must not exist:</p>

<pre><code>sysopen my $fh, $path, O_WRONLY|O_EXCL|O_CREAT        or die $!;
sysopen my $fh, $path, O_WRONLY|O_EXCL|O_CREAT, 0666  or die $!;</code></pre>

<p>To open file for appending, create if necessary:</p>

<pre><code>open my $fh, &#39;&gt;&gt;&#39;, $path                              or die $!;
sysopen my $fh, $path, O_WRONLY|O_APPEND|O_CREAT      or die $!;
sysopen my $fh, $path, O_WRONLY|O_APPEND|O_CREAT, 0666 or die $!;</code></pre>

<p>To open file for appending, file must exist:</p>

<pre><code>sysopen my $fh, $path, O_WRONLY|O_APPEND              or die $!;</code></pre>

<p>To open file for update, file must exist:</p>

<pre><code>open my $fh, &#39;+&lt;&#39;, $path                              or die $!;
sysopen my $fh, $path, O_RDWR                         or die $!;</code></pre>

<p>To open file for update, create file if necessary:</p>

<pre><code>sysopen my $fh, $path, O_RDWR|O_CREAT                 or die $!;
sysopen my $fh, $path, O_RDWR|O_CREAT, 0666           or die $!;</code></pre>

<p>To open file for update, file must not exist:</p>

<pre><code>sysopen my $fh, $path, O_RDWR|O_EXCL|O_CREAT          or die $!;
sysopen my $fh, $path, O_RDWR|O_EXCL|O_CREAT, 0666    or die $!;</code></pre>

<p>To open a file without blocking, creating if necessary:</p>

<pre><code>sysopen my $fh, &#39;/foo/somefile&#39;, O_WRONLY|O_NDELAY|O_CREAT
    or die &quot;can&#39;t open /foo/somefile: $!&quot;:</code></pre>

<p>Be warned that neither creation nor deletion of files is guaranteed to be an atomic operation over NFS. That is, two processes might both successfully create or unlink the same file! Therefore O_EXCL isn&#39;t as exclusive as you might wish.</p>

<p>See also <a href="perlopentut.html">perlopentut</a>.</p>

<h2 id="Why-do-I-sometimes-get-an-&quot;Argument-list-too-long&quot;-when-I-use-&lt;*&gt;?"><a class="permalink" href="perlfaq5.html#Why-do-I-sometimes-get-an-%22Argument-list-too-long%22-when-I-use-%3C*%3E?">#</a><a id="Why"></a><a id="Why-do-I-sometimes-get-an-Argument-list-too-long-when-I-use"></a>Why do I sometimes get an &quot;Argument list too long&quot; when I use &lt;*&gt;? </h2>

<p>The <code>&lt;&gt;</code> operator performs a globbing operation (see above). In Perl versions earlier than v5.6.0, the internal glob() operator forks csh(1) to do the actual glob expansion, but csh can&#39;t handle more than 127 items and so gives the error message <code>Argument list too long</code>. People who installed tcsh as csh won&#39;t have this problem, but their users may be surprised by it.</p>

<p>To get around this, either upgrade to Perl v5.6.0 or later, do the glob yourself with readdir() and patterns, or use a module like <a href="./File::Glob.html">File::Glob</a>, one that doesn&#39;t use the shell to do globbing.</p>

<h2 id="How-can-I-open-a-file-named-with-a-leading-&quot;&gt;&quot;-or-trailing-blanks?"><a class="permalink" href="perlfaq5.html#How-can-I-open-a-file-named-with-a-leading-%22%3E%22-or-trailing-blanks?">#</a><a id="How16"></a><a id="How-can-I-open-a-file-named-with-a-leading-or-trailing-blanks"></a>How can I open a file named with a leading &quot;&gt;&quot; or trailing blanks? </h2>

<p>(contributed by Brian McCauley)</p>

<p>The special two-argument form of Perl&#39;s open() function ignores trailing blanks in filenames and infers the mode from certain leading characters (or a trailing &quot;|&quot;). In older versions of Perl this was the only version of open() and so it is prevalent in old code and books.</p>

<p>Unless you have a particular reason to use the two-argument form you should use the three-argument form of open() which does not treat any characters in the filename as special.</p>

<pre><code>open my $fh, &quot;&lt;&quot;, &quot;  file  &quot;;  # filename is &quot;   file   &quot;
open my $fh, &quot;&gt;&quot;, &quot;&gt;file&quot;;     # filename is &quot;&gt;file&quot;</code></pre>

<h2 id="How-can-I-reliably-rename-a-file?"><a class="permalink" href="perlfaq5.html#How-can-I-reliably-rename-a-file?">#</a><a id="How17"></a><a id="How-can-I-reliably-rename-a-file"></a>How can I reliably rename a file?    </h2>

<p>If your operating system supports a proper mv(1) utility or its functional equivalent, this works:</p>

<pre><code>rename($old, $new) or system(&quot;mv&quot;, $old, $new);</code></pre>

<p>It may be more portable to use the <a href="./File::Copy.html">File::Copy</a> module instead. You just copy to the new file to the new name (checking return values), then delete the old one. This isn&#39;t really the same semantically as a <code>rename()</code>, which preserves meta-information like permissions, timestamps, inode info, etc.</p>

<h2 id="How-can-I-lock-a-file?"><a class="permalink" href="perlfaq5.html#How-can-I-lock-a-file?">#</a><a id="How18"></a><a id="How-can-I-lock-a-file"></a>How can I lock a file?   </h2>

<p>Perl&#39;s builtin flock() function (see <a href="perlfunc.html">perlfunc</a> for details) will call flock(2) if that exists, fcntl(2) if it doesn&#39;t (on perl version 5.004 and later), and lockf(3) if neither of the two previous system calls exists. On some systems, it may even use a different form of native locking. Here are some gotchas with Perl&#39;s flock():</p>

<ol>

<li><p>Produces a fatal error if none of the three system calls (or their close equivalent) exists.</p>

</li>
<li><p>lockf(3) does not provide shared locking, and requires that the filehandle be open for writing (or appending, or read/writing).</p>

</li>
<li><p>Some versions of flock() can&#39;t lock files over a network (e.g. on NFS file systems), so you&#39;d need to force the use of fcntl(2) when you build Perl. But even this is dubious at best. See the flock entry of <a href="perlfunc.html">perlfunc</a> and the <i>INSTALL</i> file in the source distribution for information on building Perl to do this.</p>

<p>Two potentially non-obvious but traditional flock semantics are that it waits indefinitely until the lock is granted, and that its locks are <i>merely advisory</i>. Such discretionary locks are more flexible, but offer fewer guarantees. This means that files locked with flock() may be modified by programs that do not also use flock(). Cars that stop for red lights get on well with each other, but not with cars that don&#39;t stop for red lights. See the perlport manpage, your port&#39;s specific documentation, or your system-specific local manpages for details. It&#39;s best to assume traditional behavior if you&#39;re writing portable programs. (If you&#39;re not, you should as always feel perfectly free to write for your own system&#39;s idiosyncrasies (sometimes called &quot;features&quot;). Slavish adherence to portability concerns shouldn&#39;t get in the way of your getting your job done.)</p>

<p>For more information on file locking, see also <a href="perlopentut.html#File-Locking">&quot;File Locking&quot; in perlopentut</a> if you have it (new for 5.6).</p>

</li>
</ol>

<h2 id="Why-can&#39;t-I-just-open(FH,-&quot;&gt;file.lock&quot;)?"><a class="permalink" href="perlfaq5.html#Why-can&#39;t-I-just-open(FH,-%22%3Efile.lock%22)?">#</a><a id="Why1"></a><a id="Why-cant-I-just-open-FH-file.lock"></a>Why can&#39;t I just open(FH, &quot;&gt;file.lock&quot;)? </h2>

<p>A common bit of code <b>NOT TO USE</b> is this:</p>

<pre><code>sleep(3) while -e &#39;file.lock&#39;;    # PLEASE DO NOT USE
open my $lock, &#39;&gt;&#39;, &#39;file.lock&#39;; # THIS BROKEN CODE</code></pre>

<p>This is a classic race condition: you take two steps to do something which must be done in one. That&#39;s why computer hardware provides an atomic test-and-set instruction. In theory, this &quot;ought&quot; to work:</p>

<pre><code>sysopen my $fh, &quot;file.lock&quot;, O_WRONLY|O_EXCL|O_CREAT
    or die &quot;can&#39;t open  file.lock: $!&quot;;</code></pre>

<p>except that lamentably, file creation (and deletion) is not atomic over NFS, so this won&#39;t work (at least, not every time) over the net. Various schemes involving link() have been suggested, but these tend to involve busy-wait, which is also less than desirable.</p>

<h2 id="I-still-don&#39;t-get-locking.-I-just-want-to-increment-the-number-in-the-file.-How-can-I-do-this?"><a class="permalink" href="perlfaq5.html#I-still-don&#39;t-get-locking.-I-just-want-to-increment-the-number-in-the-file.-How-can-I-do-this?">#</a><a id="I"></a><a id="I-still-dont-get-locking.-I-just-want-to-increment-the-number-in-the-file.-How-can-I-do-this"></a>I still don&#39;t get locking. I just want to increment the number in the file. How can I do this?  </h2>

<p>Didn&#39;t anyone ever tell you web-page hit counters were useless? They don&#39;t count number of hits, they&#39;re a waste of time, and they serve only to stroke the writer&#39;s vanity. It&#39;s better to pick a random number; they&#39;re more realistic.</p>

<p>Anyway, this is what you can do if you can&#39;t help yourself.</p>

<pre><code>use Fcntl qw(:DEFAULT :flock);
sysopen my $fh, &quot;numfile&quot;, O_RDWR|O_CREAT or die &quot;can&#39;t open numfile: $!&quot;;
flock $fh, LOCK_EX                        or die &quot;can&#39;t flock numfile: $!&quot;;
my $num = &lt;$fh&gt; || 0;
seek $fh, 0, 0                            or die &quot;can&#39;t rewind numfile: $!&quot;;
truncate $fh, 0                           or die &quot;can&#39;t truncate numfile: $!&quot;;
(print $fh $num+1, &quot;\n&quot;)                  or die &quot;can&#39;t write numfile: $!&quot;;
close $fh                                 or die &quot;can&#39;t close numfile: $!&quot;;</code></pre>

<p>Here&#39;s a much better web-page hit counter:</p>

<pre><code>$hits = int( (time() - 850_000_000) / rand(1_000) );</code></pre>

<p>If the count doesn&#39;t impress your friends, then the code might. :-)</p>

<h2 id="All-I-want-to-do-is-append-a-small-amount-of-text-to-the-end-of-a-file.-Do-I-still-have-to-use-locking?"><a class="permalink" href="perlfaq5.html#All-I-want-to-do-is-append-a-small-amount-of-text-to-the-end-of-a-file.-Do-I-still-have-to-use-locking?">#</a><a id="All"></a><a id="All-I-want-to-do-is-append-a-small-amount-of-text-to-the-end-of-a-file.-Do-I-still-have-to-use-locking"></a>All I want to do is append a small amount of text to the end of a file. Do I still have to use locking?  </h2>

<p>If you are on a system that correctly implements <code>flock</code> and you use the example appending code from &quot;perldoc -f flock&quot; everything will be OK even if the OS you are on doesn&#39;t implement append mode correctly (if such a system exists). So if you are happy to restrict yourself to OSs that implement <code>flock</code> (and that&#39;s not really much of a restriction) then that is what you should do.</p>

<p>If you know you are only going to use a system that does correctly implement appending (i.e. not Win32) then you can omit the <code>seek</code> from the code in the previous answer.</p>

<p>If you know you are only writing code to run on an OS and filesystem that does implement append mode correctly (a local filesystem on a modern Unix for example), and you keep the file in block-buffered mode and you write less than one buffer-full of output between each manual flushing of the buffer then each bufferload is almost guaranteed to be written to the end of the file in one chunk without getting intermingled with anyone else&#39;s output. You can also use the <code>syswrite</code> function which is simply a wrapper around your system&#39;s <code>write(2)</code> system call.</p>

<p>There is still a small theoretical chance that a signal will interrupt the system-level <code>write()</code> operation before completion. There is also a possibility that some STDIO implementations may call multiple system level <code>write()</code>s even if the buffer was empty to start. There may be some systems where this probability is reduced to zero, and this is not a concern when using <code>:perlio</code> instead of your system&#39;s STDIO.</p>

<h2 id="How-do-I-randomly-update-a-binary-file?"><a class="permalink" href="perlfaq5.html#How-do-I-randomly-update-a-binary-file?">#</a><a id="How19"></a><a id="How-do-I-randomly-update-a-binary-file"></a>How do I randomly update a binary file? </h2>

<p>If you&#39;re just trying to patch a binary, in many cases something as simple as this works:</p>

<pre><code class="plaintext">perl -i -pe &#39;s{window manager}{window mangler}g&#39; /usr/bin/emacs</code></pre>

<p>However, if you have fixed sized records, then you might do something more like this:</p>

<pre><code>my $RECSIZE = 220; # size of record, in bytes
my $recno   = 37;  # which record to update
open my $fh, &#39;+&lt;&#39;, &#39;somewhere&#39; or die &quot;can&#39;t update somewhere: $!&quot;;
seek $fh, $recno * $RECSIZE, 0;
read $fh, $record, $RECSIZE == $RECSIZE or die &quot;can&#39;t read record $recno: $!&quot;;
# munge the record
seek $fh, -$RECSIZE, 1;
print $fh $record;
close $fh;</code></pre>

<p>Locking and error checking are left as an exercise for the reader. Don&#39;t forget them or you&#39;ll be quite sorry.</p>

<h2 id="How-do-I-get-a-file&#39;s-timestamp-in-perl?"><a class="permalink" href="perlfaq5.html#How-do-I-get-a-file&#39;s-timestamp-in-perl?">#</a><a id="How20"></a><a id="How-do-I-get-a-files-timestamp-in-perl"></a>How do I get a file&#39;s timestamp in perl?  </h2>

<p>If you want to retrieve the time at which the file was last read, written, or had its meta-data (owner, etc) changed, you use the <b>-A</b>, <b>-M</b>, or <b>-C</b> file test operations as documented in <a href="perlfunc.html">perlfunc</a>. These retrieve the age of the file (measured against the start-time of your program) in days as a floating point number. Some platforms may not have all of these times. See <a href="perlport.html">perlport</a> for details. To retrieve the &quot;raw&quot; time in seconds since the epoch, you would call the stat function, then use <code>localtime()</code>, <code>gmtime()</code>, or <code>POSIX::strftime()</code> to convert this into human-readable form.</p>

<p>Here&#39;s an example:</p>

<pre><code>my $write_secs = (stat($file))[9];
printf &quot;file %s updated at %s\n&quot;, $file,
    scalar localtime($write_secs);</code></pre>

<p>If you prefer something more legible, use the File::stat module (part of the standard distribution in version 5.004 and later):</p>

<pre><code># error checking left as an exercise for reader.
use File::stat;
use Time::localtime;
my $date_string = ctime(stat($file)-&gt;mtime);
print &quot;file $file updated at $date_string\n&quot;;</code></pre>

<p>The POSIX::strftime() approach has the benefit of being, in theory, independent of the current locale. See <a href="perllocale.html">perllocale</a> for details.</p>

<h2 id="How-do-I-set-a-file&#39;s-timestamp-in-perl?"><a class="permalink" href="perlfaq5.html#How-do-I-set-a-file&#39;s-timestamp-in-perl?">#</a><a id="How21"></a><a id="How-do-I-set-a-files-timestamp-in-perl"></a>How do I set a file&#39;s timestamp in perl?  </h2>

<p>You use the utime() function documented in <a href="perlfunc.html#utime">&quot;utime&quot; in perlfunc</a>. By way of example, here&#39;s a little program that copies the read and write times from its first argument to all the rest of them.</p>

<pre><code>if (@ARGV &lt; 2) {
    die &quot;usage: cptimes timestamp_file other_files ...\n&quot;;
}
my $timestamp = shift;
my($atime, $mtime) = (stat($timestamp))[8,9];
utime $atime, $mtime, @ARGV;</code></pre>

<p>Error checking is, as usual, left as an exercise for the reader.</p>

<p>The perldoc for utime also has an example that has the same effect as touch(1) on files that <i>already exist</i>.</p>

<p>Certain file systems have a limited ability to store the times on a file at the expected level of precision. For example, the FAT and HPFS filesystem are unable to create dates on files with a finer granularity than two seconds. This is a limitation of the filesystems, not of utime().</p>

<h2 id="How-do-I-print-to-more-than-one-file-at-once?"><a class="permalink" href="perlfaq5.html#How-do-I-print-to-more-than-one-file-at-once?">#</a><a id="How22"></a><a id="How-do-I-print-to-more-than-one-file-at-once"></a>How do I print to more than one file at once? </h2>

<p>To connect one filehandle to several output filehandles, you can use the <a href="./IO::Tee.html">IO::Tee</a> or <a href="https://perldoc.perl.org/5.35.0/Tie::FileHandle::Multiplex">Tie::FileHandle::Multiplex</a> modules.</p>

<p>If you only have to do this once, you can print individually to each filehandle.</p>

<pre><code>for my $fh ($fh1, $fh2, $fh3) { print $fh &quot;whatever\n&quot; }</code></pre>

<h2 id="How-can-I-read-in-an-entire-file-all-at-once?"><a class="permalink" href="perlfaq5.html#How-can-I-read-in-an-entire-file-all-at-once?">#</a><a id="How23"></a><a id="How-can-I-read-in-an-entire-file-all-at-once"></a>How can I read in an entire file all at once?  </h2>

<p>The customary Perl approach for processing all the lines in a file is to do so one line at a time:</p>

<pre><code>open my $input, &#39;&lt;&#39;, $file or die &quot;can&#39;t open $file: $!&quot;;
while (&lt;$input&gt;) {
    chomp;
    # do something with $_
}
close $input or die &quot;can&#39;t close $file: $!&quot;;</code></pre>

<p>This is tremendously more efficient than reading the entire file into memory as an array of lines and then processing it one element at a time, which is often--if not almost always--the wrong approach. Whenever you see someone do this:</p>

<pre><code>my @lines = &lt;INPUT&gt;;</code></pre>

<p>You should think long and hard about why you need everything loaded at once. It&#39;s just not a scalable solution.</p>

<p>If you &quot;mmap&quot; the file with the File::Map module from CPAN, you can virtually load the entire file into a string without actually storing it in memory:</p>

<pre><code>use File::Map qw(map_file);

map_file my $string, $filename;</code></pre>

<p>Once mapped, you can treat <code>$string</code> as you would any other string. Since you don&#39;t necessarily have to load the data, mmap-ing can be very fast and may not increase your memory footprint.</p>

<p>You might also find it more fun to use the standard <a href="./Tie::File.html">Tie::File</a> module, or the <a href="DB_File.html">DB_File</a> module&#39;s <code>$DB_RECNO</code> bindings, which allow you to tie an array to a file so that accessing an element of the array actually accesses the corresponding line in the file.</p>

<p>If you want to load the entire file, you can use the <a href="./Path::Tiny.html">Path::Tiny</a> module to do it in one simple and efficient step:</p>

<pre><code>use Path::Tiny;

my $all_of_it = path($filename)-&gt;slurp; # entire file in scalar
my @all_lines = path($filename)-&gt;lines; # one line per element</code></pre>

<p>Or you can read the entire file contents into a scalar like this:</p>

<pre><code>my $var;
{
    local $/;
    open my $fh, &#39;&lt;&#39;, $file or die &quot;can&#39;t open $file: $!&quot;;
    $var = &lt;$fh&gt;;
}</code></pre>

<p>That temporarily undefs your record separator, and will automatically close the file at block exit. If the file is already open, just use this:</p>

<pre><code>my $var = do { local $/; &lt;$fh&gt; };</code></pre>

<p>You can also use a localized <code>@ARGV</code> to eliminate the <code>open</code>:</p>

<pre><code>my $var = do { local( @ARGV, $/ ) = $file; &lt;&gt; };</code></pre>

<p>For ordinary files you can also use the <code>read</code> function.</p>

<pre><code>read( $fh, $var, -s $fh );</code></pre>

<p>That third argument tests the byte size of the data on the <code>$fh</code> filehandle and reads that many bytes into the buffer <code>$var</code>.</p>

<h2 id="How-can-I-read-in-a-file-by-paragraphs?"><a class="permalink" href="perlfaq5.html#How-can-I-read-in-a-file-by-paragraphs?">#</a><a id="How24"></a><a id="How-can-I-read-in-a-file-by-paragraphs"></a>How can I read in a file by paragraphs? </h2>

<p>Use the <code>$/</code> variable (see <a href="perlvar.html">perlvar</a> for details). You can either set it to <code>&quot;&quot;</code> to eliminate empty paragraphs (<code>&quot;abc\n\n\n\ndef&quot;</code>, for instance, gets treated as two paragraphs and not three), or <code>&quot;\n\n&quot;</code> to accept empty paragraphs.</p>

<p>Note that a blank line must have no blanks in it. Thus <span style="white-space: nowrap;"><code>&quot;fred\n \nstuff\n\n&quot;</code></span> is one paragraph, but <code>&quot;fred\n\nstuff\n\n&quot;</code> is two.</p>

<h2 id="How-can-I-read-a-single-character-from-a-file?-From-the-keyboard?"><a class="permalink" href="perlfaq5.html#How-can-I-read-a-single-character-from-a-file?-From-the-keyboard?">#</a><a id="How25"></a><a id="How-can-I-read-a-single-character-from-a-file-From-the-keyboard"></a>How can I read a single character from a file? From the keyboard?  </h2>

<p>You can use the builtin <code>getc()</code> function for most filehandles, but it won&#39;t (easily) work on a terminal device. For STDIN, either use the Term::ReadKey module from CPAN or use the sample code in <a href="perlfunc.html#getc">&quot;getc&quot; in perlfunc</a>.</p>

<p>If your system supports the portable operating system programming interface (POSIX), you can use the following code, which you&#39;ll note turns off echo processing as well.</p>

<pre><code>#!/usr/bin/perl -w
use strict;
$| = 1;
for (1..4) {
    print &quot;gimme: &quot;;
    my $got = getone();
    print &quot;--&gt; $got\n&quot;;
}
exit;

BEGIN {
    use POSIX qw(:termios_h);

    my ($term, $oterm, $echo, $noecho, $fd_stdin);

    my $fd_stdin = fileno(STDIN);

    $term     = POSIX::Termios-&gt;new();
    $term-&gt;getattr($fd_stdin);
    $oterm     = $term-&gt;getlflag();

    $echo     = ECHO | ECHOK | ICANON;
    $noecho   = $oterm &amp; ~$echo;

    sub cbreak {
        $term-&gt;setlflag($noecho);
        $term-&gt;setcc(VTIME, 1);
        $term-&gt;setattr($fd_stdin, TCSANOW);
    }

    sub cooked {
        $term-&gt;setlflag($oterm);
        $term-&gt;setcc(VTIME, 0);
        $term-&gt;setattr($fd_stdin, TCSANOW);
    }

    sub getone {
        my $key = &#39;&#39;;
        cbreak();
        sysread(STDIN, $key, 1);
        cooked();
        return $key;
    }
}

END { cooked() }</code></pre>

<p>The Term::ReadKey module from CPAN may be easier to use. Recent versions include also support for non-portable systems as well.</p>

<pre><code>use Term::ReadKey;
open my $tty, &#39;&lt;&#39;, &#39;/dev/tty&#39;;
print &quot;Gimme a char: &quot;;
ReadMode &quot;raw&quot;;
my $key = ReadKey 0, $tty;
ReadMode &quot;normal&quot;;
printf &quot;\nYou said %s, char number %03d\n&quot;,
    $key, ord $key;</code></pre>

<h2 id="How-can-I-tell-whether-there&#39;s-a-character-waiting-on-a-filehandle?"><a class="permalink" href="perlfaq5.html#How-can-I-tell-whether-there&#39;s-a-character-waiting-on-a-filehandle?">#</a><a id="How26"></a><a id="How-can-I-tell-whether-theres-a-character-waiting-on-a-filehandle"></a>How can I tell whether there&#39;s a character waiting on a filehandle?</h2>

<p>The very first thing you should do is look into getting the Term::ReadKey extension from CPAN. As we mentioned earlier, it now even has limited support for non-portable (read: not open systems, closed, proprietary, not POSIX, not Unix, etc.) systems.</p>

<p>You should also check out the Frequently Asked Questions list in comp.unix.* for things like this: the answer is essentially the same. It&#39;s very system-dependent. Here&#39;s one solution that works on BSD systems:</p>

<pre><code>sub key_ready {
    my($rin, $nfd);
    vec($rin, fileno(STDIN), 1) = 1;
    return $nfd = select($rin,undef,undef,0);
}</code></pre>

<p>If you want to find out how many characters are waiting, there&#39;s also the FIONREAD ioctl call to be looked at. The <i>h2ph</i> tool that comes with Perl tries to convert C include files to Perl code, which can be <code>require</code>d. FIONREAD ends up defined as a function in the <i>sys/ioctl.ph</i> file:</p>

<pre><code>require &#39;./sys/ioctl.ph&#39;;

$size = pack(&quot;L&quot;, 0);
ioctl(FH, FIONREAD(), $size)    or die &quot;Couldn&#39;t call ioctl: $!\n&quot;;
$size = unpack(&quot;L&quot;, $size);</code></pre>

<p>If <i>h2ph</i> wasn&#39;t installed or doesn&#39;t work for you, you can <i>grep</i> the include files by hand:</p>

<pre><code class="plaintext">% grep FIONREAD /usr/include/*/*
/usr/include/asm/ioctls.h:#define FIONREAD      0x541B</code></pre>

<p>Or write a small C program using the editor of champions:</p>

<pre><code>% cat &gt; fionread.c
#include &lt;sys/ioctl.h&gt;
main() {
    printf(&quot;%#08x\n&quot;, FIONREAD);
}
^D
% cc -o fionread fionread.c
% ./fionread
0x4004667f</code></pre>

<p>And then hard-code it, leaving porting as an exercise to your successor.</p>

<pre><code>$FIONREAD = 0x4004667f;         # XXX: opsys dependent

$size = pack(&quot;L&quot;, 0);
ioctl(FH, $FIONREAD, $size)     or die &quot;Couldn&#39;t call ioctl: $!\n&quot;;
$size = unpack(&quot;L&quot;, $size);</code></pre>

<p>FIONREAD requires a filehandle connected to a stream, meaning that sockets, pipes, and tty devices work, but <i>not</i> files.</p>

<h2 id="How-do-I-do-a-tail-f-in-perl?"><a class="permalink" href="perlfaq5.html#How-do-I-do-a-tail-f-in-perl?">#</a><a id="How27"></a><a id="How-do-I-do-a-tail--f-in-perl"></a>How do I do a <code>tail -f</code> in perl?    </h2>

<p>First try</p>

<pre><code>seek($gw_fh, 0, 1);</code></pre>

<p>The statement <code>seek($gw_fh, 0, 1)</code> doesn&#39;t change the current position, but it does clear the end-of-file condition on the handle, so that the next <code>&lt;$gw_fh&gt;</code> makes Perl try again to read something.</p>

<p>If that doesn&#39;t work (it relies on features of your stdio implementation), then you need something more like this:</p>

<pre><code>for (;;) {
  for ($curpos = tell($gw_fh); &lt;$gw_fh&gt;; $curpos =tell($gw_fh)) {
    # search for some stuff and put it into files
  }
  # sleep for a while
  seek($gw_fh, $curpos, 0);  # seek to where we had been
}</code></pre>

<p>If this still doesn&#39;t work, look into the <code>clearerr</code> method from <a href="./IO::Handle.html">IO::Handle</a>, which resets the error and end-of-file states on the handle.</p>

<p>There&#39;s also a <a href="./File::Tail.html">File::Tail</a> module from CPAN.</p>

<h2 id="How-do-I-dup()-a-filehandle-in-Perl?"><a class="permalink" href="perlfaq5.html#How-do-I-dup()-a-filehandle-in-Perl?">#</a><a id="How28"></a><a id="How-do-I-dup-a-filehandle-in-Perl"></a>How do I dup() a filehandle in Perl? </h2>

<p>If you check <a href="perlfunc.html#open">&quot;open&quot; in perlfunc</a>, you&#39;ll see that several of the ways to call open() should do the trick. For example:</p>

<pre><code>open my $log, &#39;&gt;&gt;&#39;, &#39;/foo/logfile&#39;;
open STDERR, &#39;&gt;&amp;&#39;, $log;</code></pre>

<p>Or even with a literal numeric descriptor:</p>

<pre><code>my $fd = $ENV{MHCONTEXTFD};
open $mhcontext, &quot;&lt;&amp;=$fd&quot;;  # like fdopen(3S)</code></pre>

<p>Note that &quot;&lt;&amp;STDIN&quot; makes a copy, but &quot;&lt;&amp;=STDIN&quot; makes an alias. That means if you close an aliased handle, all aliases become inaccessible. This is not true with a copied one.</p>

<p>Error checking, as always, has been left as an exercise for the reader.</p>

<h2 id="How-do-I-close-a-file-descriptor-by-number?"><a class="permalink" href="perlfaq5.html#How-do-I-close-a-file-descriptor-by-number?">#</a><a id="How29"></a><a id="How-do-I-close-a-file-descriptor-by-number"></a>How do I close a file descriptor by number?   </h2>

<p>If, for some reason, you have a file descriptor instead of a filehandle (perhaps you used <code>POSIX::open</code>), you can use the <code>close()</code> function from the <a href="POSIX.html">POSIX</a> module:</p>

<pre><code>use POSIX ();

POSIX::close( $fd );</code></pre>

<p>This should rarely be necessary, as the Perl <code>close()</code> function is to be used for things that Perl opened itself, even if it was a dup of a numeric descriptor as with <code>MHCONTEXT</code> above. But if you really have to, you may be able to do this:</p>

<pre><code>require &#39;./sys/syscall.ph&#39;;
my $rc = syscall(SYS_close(), $fd + 0);  # must force numeric
die &quot;can&#39;t sysclose $fd: $!&quot; unless $rc == -1;</code></pre>

<p>Or, just use the fdopen(3S) feature of <code>open()</code>:</p>

<pre><code>{
    open my $fh, &quot;&lt;&amp;=$fd&quot; or die &quot;Cannot reopen fd=$fd: $!&quot;;
    close $fh;
}</code></pre>

<h2 id="Why-can&#39;t-I-use-&quot;C:\temp\foo&quot;-in-DOS-paths?-Why-doesn&#39;t-`C:\temp\foo.exe`-work?"><a class="permalink" href="perlfaq5.html#Why-can&#39;t-I-use-%22C:%5Ctemp%5Cfoo%22-in-DOS-paths?-Why-doesn&#39;t-%60C:%5Ctemp%5Cfoo.exe%60-work?">#</a><a id="Why2"></a><a id="Why-cant-I-use-C:-temp-foo-in-DOS-paths-Why-doesnt-C:-temp-foo.exe-work"></a>Why can&#39;t I use &quot;C:\temp\foo&quot; in DOS paths? Why doesn&#39;t `C:\temp\foo.exe` work? </h2>

<p>Whoops! You just put a tab and a formfeed into that filename! Remember that within double quoted strings (&quot;like\this&quot;), the backslash is an escape character. The full list of these is in <a href="perlop.html#Quote-and-Quote-like-Operators">&quot;Quote and Quote-like Operators&quot; in perlop</a>. Unsurprisingly, you don&#39;t have a file called &quot;c:(tab)emp(formfeed)oo&quot; or &quot;c:(tab)emp(formfeed)oo.exe&quot; on your legacy DOS filesystem.</p>

<p>Either single-quote your strings, or (preferably) use forward slashes. Since all DOS and Windows versions since something like MS-DOS 2.0 or so have treated <code>/</code> and <code>\</code> the same in a path, you might as well use the one that doesn&#39;t clash with Perl--or the POSIX shell, ANSI C and C++, awk, Tcl, Java, or Python, just to mention a few. POSIX paths are more portable, too.</p>

<h2 id="Why-doesn&#39;t-glob(&quot;*.*&quot;)-get-all-the-files?"><a class="permalink" href="perlfaq5.html#Why-doesn&#39;t-glob(%22*.*%22)-get-all-the-files?">#</a><a id="Why3"></a><a id="Why-doesnt-glob-.-get-all-the-files"></a>Why doesn&#39;t glob(&quot;*.*&quot;) get all the files? </h2>

<p>Because even on non-Unix ports, Perl&#39;s glob function follows standard Unix globbing semantics. You&#39;ll need <code>glob(&quot;*&quot;)</code> to get all (non-hidden) files. This makes glob() portable even to legacy systems. Your port may include proprietary globbing functions as well. Check its documentation for details.</p>

<h2 id="Why-does-Perl-let-me-delete-read-only-files?-Why-does-i-clobber-protected-files?-Isn&#39;t-this-a-bug-in-Perl?"><a class="permalink" href="perlfaq5.html#Why-does-Perl-let-me-delete-read-only-files?-Why-does-i-clobber-protected-files?-Isn&#39;t-this-a-bug-in-Perl?">#</a><a id="Why4"></a><a id="Why-does-Perl-let-me-delete-read-only-files-Why-does--i-clobber-protected-files-Isnt-this-a-bug-in-Perl"></a>Why does Perl let me delete read-only files? Why does <code>-i</code> clobber protected files? Isn&#39;t this a bug in Perl?</h2>

<p>This is elaborately and painstakingly described in the <i>file-dir-perms</i> article in the &quot;Far More Than You Ever Wanted To Know&quot; collection in <a href="http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz">http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz</a> .</p>

<p>The executive summary: learn how your filesystem works. The permissions on a file say what can happen to the data in that file. The permissions on a directory say what can happen to the list of files in that directory. If you delete a file, you&#39;re removing its name from the directory (so the operation depends on the permissions of the directory, not of the file). If you try to write to the file, the permissions of the file govern whether you&#39;re allowed to.</p>

<h2 id="How-do-I-select-a-random-line-from-a-file?"><a class="permalink" href="perlfaq5.html#How-do-I-select-a-random-line-from-a-file?">#</a><a id="How30"></a><a id="How-do-I-select-a-random-line-from-a-file"></a>How do I select a random line from a file? </h2>

<p>Short of loading the file into a database or pre-indexing the lines in the file, there are a couple of things that you can do.</p>

<p>Here&#39;s a reservoir-sampling algorithm from the Camel Book:</p>

<pre><code>srand;
rand($.) &lt; 1 &amp;&amp; ($line = $_) while &lt;&gt;;</code></pre>

<p>This has a significant advantage in space over reading the whole file in. You can find a proof of this method in <i>The Art of Computer Programming</i>, Volume 2, Section 3.4.2, by Donald E. Knuth.</p>

<p>You can use the <a href="./File::Random.html">File::Random</a> module which provides a function for that algorithm:</p>

<pre><code>use File::Random qw/random_line/;
my $line = random_line($filename);</code></pre>

<p>Another way is to use the <a href="./Tie::File.html">Tie::File</a> module, which treats the entire file as an array. Simply access a random array element.</p>

<h2 id="Why-do-I-get-weird-spaces-when-I-print-an-array-of-lines?"><a class="permalink" href="perlfaq5.html#Why-do-I-get-weird-spaces-when-I-print-an-array-of-lines?">#</a><a id="Why5"></a><a id="Why-do-I-get-weird-spaces-when-I-print-an-array-of-lines"></a>Why do I get weird spaces when I print an array of lines?</h2>

<p>(contributed by brian d foy)</p>

<p>If you are seeing spaces between the elements of your array when you print the array, you are probably interpolating the array in double quotes:</p>

<pre><code>my @animals = qw(camel llama alpaca vicuna);
print &quot;animals are: @animals\n&quot;;</code></pre>

<p>It&#39;s the double quotes, not the <code>print</code>, doing this. Whenever you interpolate an array in a double quote context, Perl joins the elements with spaces (or whatever is in <code>$&quot;</code>, which is a space by default):</p>

<pre><code class="plaintext">animals are: camel llama alpaca vicuna</code></pre>

<p>This is different than printing the array without the interpolation:</p>

<pre><code>my @animals = qw(camel llama alpaca vicuna);
print &quot;animals are: &quot;, @animals, &quot;\n&quot;;</code></pre>

<p>Now the output doesn&#39;t have the spaces between the elements because the elements of <code>@animals</code> simply become part of the list to <code>print</code>:</p>

<pre><code class="plaintext">animals are: camelllamaalpacavicuna</code></pre>

<p>You might notice this when each of the elements of <code>@array</code> end with a newline. You expect to print one element per line, but notice that every line after the first is indented:</p>

<pre><code class="plaintext">this is a line
 this is another line
 this is the third line</code></pre>

<p>That extra space comes from the interpolation of the array. If you don&#39;t want to put anything between your array elements, don&#39;t use the array in double quotes. You can send it to print without them:</p>

<pre><code>print @lines;</code></pre>

<h2 id="How-do-I-traverse-a-directory-tree?"><a class="permalink" href="perlfaq5.html#How-do-I-traverse-a-directory-tree?">#</a><a id="How31"></a><a id="How-do-I-traverse-a-directory-tree"></a>How do I traverse a directory tree?</h2>

<p>(contributed by brian d foy)</p>

<p>The <a href="./File::Find.html">File::Find</a> module, which comes with Perl, does all of the hard work to traverse a directory structure. It comes with Perl. You simply call the <code>find</code> subroutine with a callback subroutine and the directories you want to traverse:</p>

<pre><code>use File::Find;

find( \&amp;wanted, @directories );

sub wanted {
    # full path in $File::Find::name
    # just filename in $_
    ... do whatever you want to do ...
}</code></pre>

<p>The <a href="./File::Find::Closures.html">File::Find::Closures</a>, which you can download from CPAN, provides many ready-to-use subroutines that you can use with <a href="./File::Find.html">File::Find</a>.</p>

<p>The <a href="./File::Finder.html">File::Finder</a>, which you can download from CPAN, can help you create the callback subroutine using something closer to the syntax of the <code>find</code> command-line utility:</p>

<pre><code>use File::Find;
use File::Finder;

my $deep_dirs = File::Finder-&gt;depth-&gt;type(&#39;d&#39;)-&gt;ls-&gt;exec(&#39;rmdir&#39;,&#39;{}&#39;);

find( $deep_dirs-&gt;as_options, @places );</code></pre>

<p>The <a href="./File::Find::Rule.html">File::Find::Rule</a> module, which you can download from CPAN, has a similar interface, but does the traversal for you too:</p>

<pre><code>use File::Find::Rule;

my @files = File::Find::Rule-&gt;file()
                         -&gt;name( &#39;*.pm&#39; )
                         -&gt;in( @INC );</code></pre>

<h2 id="How-do-I-delete-a-directory-tree?"><a class="permalink" href="perlfaq5.html#How-do-I-delete-a-directory-tree?">#</a><a id="How32"></a><a id="How-do-I-delete-a-directory-tree"></a>How do I delete a directory tree?</h2>

<p>(contributed by brian d foy)</p>

<p>If you have an empty directory, you can use Perl&#39;s built-in <code>rmdir</code>. If the directory is not empty (so, with files or subdirectories), you either have to empty it yourself (a lot of work) or use a module to help you.</p>

<p>The <a href="./File::Path.html">File::Path</a> module, which comes with Perl, has a <code>remove_tree</code> which can take care of all of the hard work for you:</p>

<pre><code>use File::Path qw(remove_tree);

remove_tree( @directories );</code></pre>

<p>The <a href="./File::Path.html">File::Path</a> module also has a legacy interface to the older <code>rmtree</code> subroutine.</p>

<h2 id="How-do-I-copy-an-entire-directory?"><a class="permalink" href="perlfaq5.html#How-do-I-copy-an-entire-directory?">#</a><a id="How33"></a><a id="How-do-I-copy-an-entire-directory"></a>How do I copy an entire directory?</h2>

<p>(contributed by Shlomi Fish)</p>

<p>To do the equivalent of <code>cp -R</code> (i.e. copy an entire directory tree recursively) in portable Perl, you&#39;ll either need to write something yourself or find a good CPAN module such as <a href="./File::Copy::Recursive.html">File::Copy::Recursive</a>.</p>

<h1 id="AUTHOR-AND-COPYRIGHT"><a class="permalink" href="perlfaq5.html#AUTHOR-AND-COPYRIGHT">#</a><a id="AUTHOR"></a>AUTHOR AND COPYRIGHT</h1>

<p>Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and other authors as noted. All rights reserved.</p>

<p>This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself.</p>

<p>Irrespective of its distribution, all code examples here are in the public domain. You are permitted and encouraged to use this code and any derivatives thereof in your own programs for fun or for profit as you see fit. A simple comment in the code giving credit to the FAQ would be courteous but is not required.</p>


      </div>
      <div id="footer">
        <p>Perldoc Browser is maintained by Dan Book (<a href="https://metacpan.org/author/DBOOK">DBOOK</a>). Please contact him via the <a href="https://github.com/Grinnz/perldoc-browser/issues">GitHub issue tracker</a> or <a href="mailto:dbook@cpan.org">email</a> regarding any issues with the site itself, search, or rendering of documentation.</p>

<p>The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via the <a href="https://github.com/Perl/perl5/issues">Perl issue tracker</a>, the <a href="https://lists.perl.org/list/perl5-porters.html">mailing list</a>, or <a href="https://kiwiirc.com/client/irc.perl.org/p5p">IRC</a> to report any issues with the contents or format of the documentation.</p>


      </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js" integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g==" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js" integrity="sha512-ubuT8Z88WxezgSqf3RLuNi5lmjstiJcyezx34yIU2gAHonIi27Na7atqzUZCOoY4CExaoFumzOsFQ2Ch+I/HCw==" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
    <script src="../highlight.pack.js"></script>
    <script>hljs.highlightAll();</script>
  </body>
</html>
